// import Mock from 'mockjs';

const state = {
    items: [],
}

// mutattions
const mutations = {
    // 添加商品到购物车
    pushProductToCart(state, { id, imgUrl, title, price, quantity, discount }) {
        if (!quantity) {
            quantity = 1;
        }
        state.items.push({ id, imgUrl, title, price, quantity, discount });
    },

    // 增加商品数量
    incrementItemQuanTity(state, { id, quantity }) {
        let cartItem = state.items.find(item => item.id == id);
        cartItem.quantity += quantity;
    },

    // 清空购物车
    setCartItems(state, { items }) {
        state.items = items;
    },

    // 删除购物车的商品
    deleteCartItem(state, id) {
        let index = state.items.findIndex(item => item.id == id);
        if (index >= 0) {
            state.items.splice(index, 1);
        }
    }
}

// getters

const getters = {
    // 计算总价
    cartTotalPrice: state => {
        return state.items.reduce((total, produce) => {
            return total + produce.price * produce.discount * produce.quantity;
        }, 0)
    },


    // 计算购物车中单项商品的价格
    cartItemPrice: state => (id, price) => {
        const cartItem = state.items.find(item => item.id == id);
        if (cartItem) {
            return price * cartItem.quantity
        }
    },

    // 获取购物车商品的数量
    itemsCount: state => {
        if (!state.length) {
            return 0
        }
        return state.length;
    }
}

// actions

const actions = {
    // 增加任意数量的商品到购物车
    addProductToCart({ state, commit }, { id, imgUrl, title, price, inventory, quantity }) {
        if (inventory > 0) {
            const cartItem = state.items.find(item => item.id == id);
            if (cartItem) {
                commit('pushProductToCart', { id, imgUrl }, title, price, quantity);
            } else {
                commit('incrementItemQuanTity', { id, quantity })
            }
        }
    }
}

// 导出
export default {
    namespaced: true,
    state,
    mutations,
    getters,
    actions
}